<template>
  <ProTable
    ref="tableRef"
    :fetchListApi="_getOnlineDevice"
    :columns="columns"
    :height="600"
    row-key="deviceId"
    :onValuesChange="changeFormState"
  >
    <template #operation="{ record }">
      <b-button icon="edit" type="link" @click="fastRelaDevice(record)"
        >选择</b-button
      >
    </template>
  </ProTable>
</template>

<script setup lang="tsx">
import { computed, ref } from 'vue';
import {
  Col,
  FormItemRest,
  Input,
  Row,
  Select,
  TreeSelect,
} from 'ant-design-vue';
import { ProTable, ProTableProps } from '@/components/ProTable/index';
import { listToEnum, listToOption } from '@/utils/utils';
import { getProjectData } from '@/api/config';
import { getModel } from '@/api/device';
import { fetchDictsOfType } from '@/api/dict';
import { getOnlineDevice } from '@/api/push';
import { getModelInfoById } from '@/api/push';

const modListOption = ref<Global.Option[]>([]);
const getModelOptions = ref<Global.Option[]>([]);
const changeFormState = async (formState: any) => {
  if (formState.deviceType) {
    console.log(formState.deviceType, 'deviceType');

    const res = await getModelInfoById({
      type: formState.deviceType,
      modelIds: '',
    });
    modListOption.value = listToOption(res.data, 'model', 'modelId', 'string');
  } else {
    modListOption.value = [];
  }
};

const columnsOptions = computed(() => {
  return modListOption.value.length
    ? modListOption.value
    : getModelOptions.value;
});

defineOptions({
  name: 'DeviceList',
});

const tableRef = ref();
const _getOnlineDevice = (params: any) => {
  const projectId = params.projectId?.join() || undefined;
  return getOnlineDevice({
    ...params,
    projectId,
  });
};
const sysDeviceModeEnum = ref<Record<string, any>>({});
const modListEnum = ref<Record<string, any>>({});
const projectData = ref([]);
let projectDataAllNum = 0;
const init = () => {
  fetchDictsOfType(['sys_device_mode']).then((res: any) => {
    const { sys_device_mode } = res.data;
    sysDeviceModeEnum.value = listToEnum(
      sys_device_mode,
      'dictValue',
      'dictLabel',
    );
  });
  getModel().then((res: any) => {
    modListEnum.value = listToEnum(res.data, 'modelId', 'model');
    getModelOptions.value = listToOption(res.data, 'model', 'modelId');
  });

  const countProjectNodes = (tree: any) => {
    let count = 0;
    tree.forEach((node: any) => {
      if (node.children && node.children.length > 0) {
        count += countProjectNodes(node.children);
      } else {
        count++;
      }
    });
    return count;
  };
  getProjectData().then((res: any) => {
    projectData.value = res.data;
    projectDataAllNum = countProjectNodes(res.data);
  });
};
init();
const columns = computed<ProTableProps['columns']>(() => [
  {
    title: '设备序列号',
    dataIndex: 'code',
    hideInSearch: true,
  },
  {
    title: '设备序列号',
    dataIndex: 'deviceCode',
    hideInTable: true,
  },
  {
    title: '小版本号',
    dataIndex: 'versionCode',
    hideInTable: true,
    hideInSearch: true,
  },
  {
    title: '软件版本',
    dataIndex: 'softwareVersion',
    width: 100,
    hideInSearch: true,
    customRender({ record, text }) {
      return `${record.softwareVersion || ''}${record.versionCode ? `(${record.versionCode})` : ''}`;
    },
    // fixed: 'left',
  },
  {
    title: '软件版本',
    dataIndex: 'version',
    width: 100,
    hideInTable: true,
    customSearchRender(state) {
      return (
        <FormItemRest>
          <Row gutter={8}>
            <Col span={12}>
              <Input
                v-model:value={state.softwareVersion}
                placeholder='请输入软件版本'
              />
            </Col>
            <Col span={12}>
              <Input
                v-model:value={state.versionCode}
                placeholder='请输入编译版本'
              />
            </Col>
          </Row>
        </FormItemRest>
      );
    },
  },
  {
    title: '固件版本',
    dataIndex: 'firmwareVersion',
  },
  {
    title: '设备类型',
    dataIndex: 'deviceType',
    valueEnum: { ...sysDeviceModeEnum.value },
    width: 100,
  },
  {
    title: '设备型号',
    dataIndex: 'model',
    hideInSearch: true,
  },
  {
    title: '设备型号',
    dataIndex: 'modelId',
    hideInTable: true,
    customSearchRender(state) {
      return (
        <Select
          v-model:value={state.modelId}
          options={columnsOptions.value}
        ></Select>
      );
    },
  },
  {
    title: '上报时间',
    dataIndex: 'reportTime',
    hideInSearch: true,
  },
  {
    title: '所属项目',
    dataIndex: 'projectId',
    hideInTable: true,
    customSearchRender(state) {
      return (
        <TreeSelect
          v-model:value={state.projectId}
          fieldNames={{ value: 'id' }}
          placeholder='请选择'
          treeData={projectData.value}
          treeCheckable={true}
          maxTagCount={0}
          allowClear={true}
          maxTagPlaceholder={(omittedValues) => {
            if (omittedValues.length == 1) {
              return omittedValues[0].label;
            } else if (omittedValues.length == projectDataAllNum) {
              return '全部';
            } else {
              return '多项目';
            }
          }}
        >
          {{
            title: ({ label, type }: any) => {
              return type == '1' ? (
                <span style='color:#bababa'>{label}</span>
              ) : (
                label
              );
            },
          }}
        </TreeSelect>
      );
    },
  },
  {
    title: '所属项目',
    hideInSearch: true,
    dataIndex: 'projectName',
  },
  {
    title: '设备地址',
    dataIndex: 'address',
    hideInSearch: true,
  },
  {
    title: '操作',
    dataIndex: 'operation',
    hideInSearch: true,
    fixed: 'right',
    width: 80,
  },
]);

const emit = defineEmits(['select']);
const fastRelaDevice = async (record: any) => {
  emit('select', record);
};
</script>
